#include "hextools.h"


void hextools_char_to_hex(unsigned char src, unsigned char* out_hex16)
{
    static char hex_table[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    out_hex16[0] = hex_table[src >> 4];
    out_hex16[1] = hex_table[src & 0x0f];
    out_hex16[2] = '\0';
}

void hextools_get_str_from_chars(char* recvdata, uint16_t len, char* out_datas, uint16_t out_datas_max_len)
{
    uint16_t index = 0;
    unsigned char hex1[3] = {0};
    for (size_t i = 0; i < len; i++)
    {
        if (out_datas_max_len <= index)
        {
            break;
        }

        hextools_char_to_hex(recvdata[i], hex1);
        out_datas[index++] = hex1[0];
        out_datas[index++] = hex1[1];
        out_datas[index++] = ' ';
    }

    out_datas[index++] = '\0';
}

void hextools_hex_to_char(unsigned char* src, unsigned char* out_hex16)
{
    uint8_t index = 0;
    if (src[1] == 'x')
    {
        index = 2;
    }

    unsigned char c = src[index++];
    *out_hex16 = ((c >= '0') && (c <= '9')) ? (c - '0') :
        ((c >= 'A') && (c <= 'F')) ? (c - 'A' + 10) :
        ((c >= 'a') && (c <= 'f')) ? (c - 'a' + 10) : 0;

    *out_hex16 = *out_hex16 << 4;

    c = src[index];

    *out_hex16 |= (((c >= '0') && (c <= '9')) ? (c - '0') :
        ((c >= 'A') && (c <= 'F')) ? (c - 'A' + 10) :
        ((c >= 'a') && (c <= 'f')) ? (c - 'a' + 10) : 0) & 0x0f;

}



uint32_t hextools_get_chars_from_hexstr(unsigned char* hexstr, uint32_t len, unsigned char splitstr, unsigned char* out_datas, uint32_t out_datas_max_len)
{
    uint32_t out_datasindex = 0;
    char onec[5];
    uint8_t onecindex = 0;
    unsigned char out_hex16;

    for (uint32_t i = 0; i < len; i++)
    {
        if (onecindex >= 5)
        {
            return -1;
        }
        onec[onecindex++] = hexstr[i];
        if (hexstr[i] == splitstr)
        {
            hextools_hex_to_char(onec, &out_hex16);
            out_datas[out_datasindex++] = out_hex16;
            onecindex = 0;
        }
    }

    if (onecindex >= 2)
    {
        hextools_hex_to_char(onec, &out_hex16);
        out_datas[out_datasindex++] = out_hex16;
        onecindex = 0;
    }

    return out_datasindex;
}
